using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Ent.Web;
using System.Collections.Generic;
using Ent.Web.Helper;
using Ent.Web.Skinner;
using Ent.Voice;

public enum Navigate { Forward, Backward, None }
public partial class Skin_wizard : Ent.Web.Skinner.MasterSkinner
{
    DynamicControl dc;
    const string ScreenId = "SCREENID";
    const string UserData = "USERDATA";
    Navigate _navigate = Navigate.None;
    Dictionary<string, object> _oldValues = null;
    public Dictionary<string, object> Values
    {
        get
        {
            if (_oldValues == null)
                _oldValues = new Dictionary<string, object>();
            return _oldValues;
        }
        set { _oldValues = value; }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        Init("basic", base.Server.MapPath("Data/web.log"), base.Server.MapPath("Data/Skin.xml"));
        dc = new DynamicControl(this.Session, "ExecutionDynaControls");
        dc.Template = (TemplateControl)this;
        if (!IsPostBack)
        {
            Session[UserData] = null;
            Session[ScreenId] = null;
        }
        
        if (Session[UserData] == null)
            _oldValues = new Dictionary<string, object>();
        else
            _oldValues = (Dictionary<string, object>)Session[UserData];

        if (!IsPostBack)
        {
            divInfo.Visible = false;
            if (Session["USERID"] == null || !((IPageWizard)this.Page).CanProcessWizard)
                return;
            Session[UserData] = Values;
            lblMandate.Text = Common.GetMandatoryText();
            dc.ClearControl();
        }
        else
        {
            ClearControls(pnlOld);
            RecreatePersistedControl();
        }
        this.PreRender += new EventHandler(Skin_wizard_PreRender);
    }
    void Skin_wizard_PreRender(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack || (Session[ScreenId] == null))
            {
                RenderScreen();
            }
            else
            {
                if (_navigate != Navigate.None)
                {
                    try
                    {
                        SaveFields();
                    }
                    catch (Exception exc)
                    {
                        string message = exc.Message;
                        if (exc.Data.Contains("UploadInfo"))
                            message += "<br/><div style=\"padding-left: 40px;\">" + exc.Data["UploadInfo"].ToString() + "</div><hr/>";
                        else
                            Common.ErrorPage(exc);
                        SetMessage(Common.GetAlertText(message));
                        ScreenIndex--;
                    }
                    RenderScreen();
                }
                else
                {
                    if (pnlOld.Controls.Count != 0)
                        pnlScreen.Controls.Add(pnlOld.Controls[0]);
                }
            }
        }
        catch (Exception exc)
        {
            Common.ErrorPage(exc);
        }
    }
    Screen[] screens = null;
    Screen[] Screens
    {
        get
        {
            if (screens == null)
            {
                Ent.Web.Screener.Sequence seq = new Ent.Web.Screener.Sequence(Server.MapPath("Data/ScreenSequence.xml"));
                screens = seq.GetScreens(((IPageWizard)this.Page).Operation);
            }
            return screens;
        }
    }
    int screenIndex = -1;
    int ScreenIndex
    {
        get
        {
            if (screenIndex == -1)
            {
                screenIndex = 0;
                string screenid = Session[ScreenId] != null ? Session[ScreenId].ToString() : "";
                if (screenid != "" && Screens != null && Screens.Length != 0)
                {
                    int del = 0;
                    if (_navigate == Navigate.Forward)
                        del = 1;
                    else if (_navigate == Navigate.Backward)
                        del = -1;
                    for (int i = 0; i < Screens.Length; i++)
                    {
                        Screen s = (Screen)Screens[i];
                        if ((s.Id == screenid) && ((Screens.Length - 1) >= i))
                        {
                            screenIndex = i + del;
                            break;
                        }
                    }
                }
                if (screenIndex < 0)
                    screenIndex = 0;
            }
            return screenIndex;
        }
        set { screenIndex = value; }
    }
    private void SaveFields()
    {
        string controlId = Session[ScreenId].ToString();
        Ent.Web.WebControl.UserControl c = (Ent.Web.WebControl.UserControl)pnlOld.FindControl(controlId);
        Dictionary<string, object> newValues = c.GetValues();

        if (newValues != null)
        {
            foreach (string k in newValues.Keys)
            {
                if (_oldValues.ContainsKey(k))
                    _oldValues[k] = newValues[k];
                else
                    _oldValues.Add(k, newValues[k]);
            }
            Session[UserData] = _oldValues;

            if (_oldValues.ContainsKey(Global.UserAgreement))
            {
                bool agree = true;
                Boolean.TryParse(_oldValues[Global.UserAgreement].ToString(), out agree);
                if (!agree)
                    Response.Redirect(ConfigurationManager.AppSettings["BaseUrl"] + "/Member/Home.aspx", false);
            }
        }
        c.Dispose();
        RemovedControl((System.Web.UI.UserControl)c);
        dc.RemoveControl(controlId);
        ClearControls(pnlOld);
    }
    private void RenderScreen()
    {
        Screen snew = null;
        lblContentName.Text = ((IPageWizard)this.Page).Operation;
        ClearControls(pnlScreen);
        pbScreen.Value = Convert.ToString((ScreenIndex * 100) / Screens.Length) + "%";
        if (ScreenIndex == Screens.Length)
        {
            Session[UserData] = null;
            Session[ScreenId] = null;
            if (((IPageWizard)this.Page).ProcessWizardData(_oldValues))
            {
                if (((IPageWizard)this.Page).SuccessCode != null)
                    Response.Redirect(ConfigurationManager.AppSettings["BaseUrl"] + "/Info.aspx?t=3&c=" + ((IPageWizard)this.Page).SuccessCode, false);
                else
                    Response.Redirect(ConfigurationManager.AppSettings["BaseUrl"] + "/Info.aspx?t=3&c=WizardSuccess", false);
            }
            else
                Response.Redirect(ConfigurationManager.AppSettings["BaseUrl"] + "/Info.aspx?t=1&c=" + ((IPageWizard)this.Page).ErrorCode, false);
            return;
        }
        snew = (Screen)Screens[ScreenIndex];
        btnNext.Visible = true;
        btnPrevious.Visible = true;
        if (ScreenIndex <= 0)
            btnPrevious.Visible = false;
        if (ScreenIndex >= Screens.Length)
            btnNext.Visible = false;

        if (snew != null)
        {
            pnlScreen.Controls.Clear();
            Ent.Web.WebControl.UserControl c = CreateControl(snew, _oldValues);
            ((IPageWizard)this.Page).SetWizard(c);
            pnlScreen.Controls.Add(c);
            c.Init();
            c.SetEvents();
            c.AddJavascript();
            lblContentName.Text += "{" + ((IPageWizard)this.Page).GetTitle(_oldValues) + "} : " + snew.Name;
            Session[ScreenId] = snew.Id;
            btnNext.OnClientClick = snew.OnSubmit;
            HtmlGenericControl body = (HtmlGenericControl)Master.FindControl("_body");
            body.Attributes.Add("onload", (snew.OnLoad != null ? snew.OnLoad : ""));

        }
    }
    
    private Ent.Web.WebControl.UserControl CreateControl(Screen screen,  Dictionary<string, object> values)
    {
        Ent.Web.WebControl.UserControl c = null;
        if (screen.Path != "")
            c = (Ent.Web.WebControl.UserControl)dc.CreateTemplateControl(screen.Id, "../" + screen.Path);
        else
        {
            if (screen.CustomPath == "" || screen.CustomPath == null || screen.FormName == "" || screen.FormName == null)
                throw new Exception("Error in Screen '" + screen.Id + "': CustomPath and FormName are mandatory when Screen path is not provided.");
            c = (Ent.Web.WebControl.UserControl)dc.CreateCustomTemplateControl(screen.Id, typeof(Ent.Web.WebControl.Form), new object[] { Server.MapPath(screen.CustomPath), screen.FormName });
        }
        c.Values = values;
        c.Parameters = screen.Parameters;
        return c;
    }
    private void RecreatePersistedControl()
    {
        Control[] ctrlList = dc.GetPersistedControls();
        if (ctrlList != null)
        {
            pnlOld.Controls.Clear();
            foreach (Control ctrl in ctrlList)
            {
                if (!HasControl(pnlOld.Controls, ctrl))
                {
                    Ent.Web.WebControl.UserControl uCtrl = (Ent.Web.WebControl.UserControl)ctrl;
                    uCtrl.Values = _oldValues;
                    ((IPageWizard)this.Page).SetWizard(uCtrl);
                    pnlOld.Controls.Add(ctrl);
                }
            }
        }
    }
    private bool HasControl(ControlCollection ctrlList, Control c)
    {
        foreach (Control ctrl in ctrlList)
        {
            if (ctrl.ID == c.ID)
                return true;
        }
        return false;
    }
    private void ClearControls(Panel p)
    {
        foreach (Control c in p.Controls)
        {
            RemovedControl(c);
        }
    }
    protected void btnNext_Click(object sender, ImageClickEventArgs e)
    {
        _navigate = Navigate.Forward;
    }
    protected void btnPrevious_Click(object sender, ImageClickEventArgs e)
    {
        _navigate = Navigate.Backward;
    }

    public void SetMessage(string message)
    {
        if (message == null)
        {
            divInfo.Visible = false;
        }
        else
        {
            divInfo.Visible = true;
            lblInfo.Text = message;
        }
    }
}
